import cookie from 'js-cookie';
import userConfig from '../config/user.config';
import store from '../store/store';
import router from '../router/router';
import { getMenuAuth } from '../api/user';
import { notification } from 'ant-design-vue';
import { getMenuRoutesByNames } from '../router/menuRoutes';
import { RouteRecordRawMy } from 'vue-router';
export function setUserToken(token: string | null) {
    if (token) return cookie.set(userConfig.TOKEN_KEY, token);
    return cookie.remove(userConfig.TOKEN_KEY);
}
export function getUserToken() {
    return cookie.get(userConfig.TOKEN_KEY);
}
export function userLogOut() {
    router.push({ name: 'login' });
    setUserToken(null);
    store.commit('RESET_STATE');
}
/**
 * 设置用户信息 menuAuth
 * @returns 
 */
export function setUserInfo() {
    return new Promise(async (resolve) => {
        try {
            const menuAuth = await getMenuAuth();
            const menuRoutes = getMenuRoutesByNames(menuAuth);
            store.commit('user/SET_MENU_ROUTES', menuRoutes);
            store.commit('user/SET_IS_LOGIN', true);
            resolve({ menuRoutes });
        } catch (error) {
            userLogOut();
            notification.warning({ message: '登录失败', description: '信息请求失败，请尝试重新登录' });
        }
    });
}
/**
 * 登录后获取跳转name
 * @param menuRoutes 
 * @returns 
 */
export function getGotoRouteName(menuRoutes: RouteRecordRawMy[] = store.state.user.menuRoutes): string | null {
    for (let index = 0; index < menuRoutes.length; index++) {
        const element = menuRoutes[index];
        if (element && element.children) {
            return getGotoRouteName(element.children);
        } else {
            return element.name;
        }
    }
    return null;
}